from scapy.all import *
import threading

# 自定义源路由头部（与 P4 代码匹配）
class SourceRouting(Packet):
    name = "SourceRouting"
    fields_desc = [
        ByteField("current_index", 0),
        ByteField("path_len", 3),  # 路径长度 3（索引 0/1/2）
        ByteField("port0", 4),     # 对应控制器规则
        ByteField("port1", 2),
        ByteField("port2", 2),
        ByteField("port3", 0)
    ]

def send_ipv4():
    """持续发送 IPv4 流量"""
    while True:
        pkt = Ether(type=0x800)/IP(dst="10.0.2.2")/Raw("IPv4 Traffic")
        sendp(pkt, iface="eth0", verbose=False)
        print("[IPv4] Sent")
        time.sleep(2)

def send_ipv6():
    """持续发送 IPv6 流量"""
    while True:
        pkt = Ether(type=0x86DD)/IPv6(dst="fe80::5678")/Raw("IPv6 Traffic")
        sendp(pkt, iface="eth0", verbose=False)
        print("[IPv6] Sent")
        time.sleep(2)

def send_sr():
    """持续发送源路由流量"""
    while True:
        pkt = Ether(type=0x1234)/SourceRouting()/Raw("SR Traffic")
        sendp(pkt, iface="eth0", verbose=False)
        print("[SR] Sent")
        time.sleep(2)

if __name__ == "__main__":
    # 多线程并发发送三种流量
    threads = [
        threading.Thread(target=send_ipv4),
        threading.Thread(target=send_ipv6),
        threading.Thread(target=send_sr)
    ]
    for t in threads:
        t.start()
    for t in threads:
        t.join()